let currelRectification = '';
let isElRectification = false;

// 只能在 renderjs 也就是 dom环境中使用

export function elRectification(el: string, currScale: string | number = 1, isKeepRatio: string | boolean = true, level: string | number = 1) {
  offelRectification();
  !el && console.error(`autofit.js：elRectification bad selector: ${el}`);
  currelRectification = el;
  const currEl = Array.from(document.querySelectorAll<HTMLElement & { originalWidth: number, originalHeight: number }>(el));
  if (currEl.length === 0) {
    console.error(`autofit.js：elRectification found no element by selector: "${el}"`);
    return;
  }
  for (const item of currEl) {
    const rectification = currScale === 1 ? 1 : Number(currScale) * Number(level);
    if (!isElRectification) {
      item.originalWidth = item.clientWidth;
      item.originalHeight = item.clientHeight;
    }
    if (isKeepRatio) {
      item.style.width = `${item.originalWidth * rectification}px`;
      item.style.height = `${item.originalHeight * rectification}px`;
    }
    else {
      item.style.width = `${100 * rectification}%`;
      item.style.height = `${100 * rectification}%`;
    }
    item.style.transform = `translateZ(0) scale(${1 / Number(currScale)})`;
    item.style.transformOrigin = `0 0`;
  }
  isElRectification = true;
}

function offelRectification() {
  if (!currelRectification)
    return;
  isElRectification = false;
  for (const item of Array.from(document.querySelectorAll<HTMLElement>(currelRectification))) {
    item.style.width = ``;
    item.style.height = ``;
    item.style.transform = ``;
  }
}
